#include <stdio.h>
#include <libusb.h>
#include <stdbool.h>

struct usb_dev_handle *tavor_udev;
bool OpenUsbPort (long int DelayTime)
{
    struct usb_bus *bus;
	struct usb_bus *usb_busses;
    struct usb_device *dev;

    usb_init();
    usb_busses = usb_find_busses();
    usb_find_devices();

    tavor_udev = NULL;
    for(bus = usb_busses;bus; bus = bus->next)
    {
        for (dev = bus->devices;dev; dev = dev->next)
        {
			printf("find one idVendor 0x%04x, idProduct 0x%04x\n", dev->descriptor.idVendor, dev->descriptor.idProduct);
            if( (dev->descriptor.idVendor == 0x8086) && (dev->descriptor.idProduct == 0xd001) )
            {
                tavor_udev = usb_open(dev);
                return tavor_udev;
            }
        }
    }
    fprintf(stderr,"tavor usb could not be found\n");
    return tavor_udev;
}

/*
bool WriteUsb (WTPCOMMAND WtpCmd,DWORD dwCmdSize)
{
    int write_bytes;
    write_bytes = usb_bulk_write(tavor_udev,0x02,(char*)&WtpCmd,dwCmdSize,200);
    return write_bytes;
}

bool ReadUsb(WTPSTATUS *WtpStatus, DWORD dwSize, PDWORD pBytesRead)
{
    int read_bytes;
    read_bytes = usb_bulk_read(tavor_udev,0x81,(char*)WtpStatus,dwSize,0);
    if(pBytesRead)*pBytesRead = read_bytes;
    return read_bytes;
}

bool ReadUsbCharBuffer (char *WtpMessage,DWORD dwSize,PDWORD pBytesRead)
{
    int result;

    if (tavor_udev == NULL)
    {
        printf (" Error: OpenUsbPort must be called prior to calling ReadUsb!");
        return FALSE;
    }
    result = usb_bulk_read(tavor_udev,0x81,(char*)WtpMessage,dwSize,100);
    if (result < 0 )
    {
        printf (" Error: ReadFile failed with error\n");
        return FALSE;
    }
    
    *pBytesRead = result;
    if (*pBytesRead != dwSize) return FALSE;
    
    return TRUE;
}
void CloseUsbPort ()
{
    if(tavor_udev)usb_close(tavor_udev);
}
*/

int main(void)
{
	printf("robert begin find usb\n");
	OpenUsbPort(100);
	printf("robert end find usb\n");
	return 0;
}
